package com.lnsoft.cac.server.handle;

import com.lnsoft.cac.server.handle.codec.Device;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
/**
 * 心跳处理类
 */
public class HeartBeatServerHandle extends ChannelInboundHandlerAdapter {

    private Device device;

    public HeartBeatServerHandle(Device device) {
        this.device = device;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.warn("heartBeat#userEventTriggered被调用:evt:{}", evt);

        if (evt instanceof IdleStateEvent) {
            int idleTimeOutNumber = device.getIdleTimeOutNumber() + 1;
            log.info("监测设备: {}  过去 {} 秒未收到数据....", device.getClientId(),idleTimeOutNumber * 63);

            if (idleTimeOutNumber > 3) {
//                log.error("终端{}:{}readTimeout大于3次，主动断开链接", device.getClientName(), device.getServerPort());
                //  连接空闲超时3次 标记设备离线（对deviceSession中的channelId置空）
//                device.setChannelId(null);

                return;
            }
            device.setIdleTimeOutNumber(idleTimeOutNumber);

            final int process = device.getProcess();
//            log.info(MessageUtil.addColour("监测设备:" + device.getClientId() + "发生第{}次超时:" + idleTimeOutNumber));
        }
        super.userEventTriggered(ctx, evt);
    }
}
